<?php
/**
 * Created by PhpStorm.
 * Date: 2016/11/16
 * Time: 下午2:05
 */
namespace app\api\controller;

use app\common\model\Alipay;
use app\common\model\MerchLevelOrder;
use app\common\model\Order;
use app\common\model\UserDistributorOrder;
use app\common\model\UserLevelOrder;
use app\common\model\Wechatpay;
use app\common\model\Users;
use think\Exception;
use think\facade\Db;

class PayNotify extends Notify
{

    //微信APP支付回调
    public function wechat()
    {
        try{
            Db::startTrans();

            $xml = file_get_contents('php://input');//获取微信返回来的通知
            if($xml=='')
            {
                $return = ['return_code'=>'FAIL','return_msg'=>'失败'];
            }else{
                file_put_contents(__DIR__.'/pay_notify/wechat.txt',$xml."\r\n",FILE_APPEND);

                //验证并获取回调数据
                $Wechatpay = new Wechatpay(1);
                $arr = $Wechatpay->getNotifyData();

                if($arr['result_code']=="SUCCESS")
                {
                    $this->successOrder($arr['out_trade_no'],$arr['total_fee']/100,$arr['cash_fee']/100,$arr['transaction_id'],'1','');
                }
                $return = ['return_code' => 'SUCCESS', 'return_msg' => 'OK'];
            }
            Db::commit();

        }catch (\Exception $exception){
            Db::rollback();
            $return = ['return_code'=>'FAIL','return_msg'=>$exception->getMessage()];
        }

        $this->wechat_return($return);

    }

    //微信小程序支付回调
    public function wechat_mini()
    {
        try{
            Db::startTrans();

            $xml = file_get_contents('php://input');//获取微信返回来的通知
            if($xml=='')
            {
                $return = ['return_code'=>'FAIL','return_msg'=>'失败'];
            }else{
                file_put_contents(__DIR__.'/pay_notify/wechat_mini.txt',$xml."\r\n",FILE_APPEND);

                //验证并获取回调数据
                $Wechatpay = new Wechatpay(2);
                $arr = $Wechatpay->getNotifyData();

                if($arr['result_code']=="SUCCESS")
                {
                    $this->successOrder($arr['out_trade_no'],$arr['total_fee']/100,$arr['cash_fee']/100,$arr['transaction_id'],'1','',1);
                }
                $return = ['return_code' => 'SUCCESS', 'return_msg' => 'OK'];
            }
            Db::commit();

        }catch (\Exception $exception){
            Db::rollback();
            $return = ['return_code'=>'FAIL','return_msg'=>$exception->getMessage()];
        }

        $this->wechat_return($return);

    }

    public function wechat_merch()
    {
        try{
            Db::startTrans();

            $xml = file_get_contents('php://input');//获取微信返回来的通知
            if($xml=='')
            {
                $return = ['return_code'=>'FAIL','return_msg'=>'失败'];
            }else{
                file_put_contents(__DIR__.'/pay_notify/wechat_merch.txt',$xml."\r\n",FILE_APPEND);

                //验证并获取回调数据
                $Wechatpay = new Wechatpay(3);
                $arr = $Wechatpay->getNotifyData();

                if($arr['result_code']=="SUCCESS")
                {
                    $this->successOrder($arr['out_trade_no'],$arr['total_fee']/100,$arr['cash_fee']/100,$arr['transaction_id'],'1','');
                }
                $return = ['return_code' => 'SUCCESS', 'return_msg' => 'OK'];
            }
            Db::commit();

        }catch (\Exception $exception){
            Db::rollback();
            $return = ['return_code'=>'FAIL','return_msg'=>$exception->getMessage()];
        }

        $this->wechat_return($return);

    }

    public function wechat_return($return){
        $xml = '<xml>';
        foreach($return as $k=>$v){
            $xml.='<'.$k.'><![CDATA['.$v.']]></'.$k.'>';
        }
        $xml.='</xml>';

        echo $xml;die();
    }

    /*支付宝回调*/
    public function alipay()
    {
        try {

            Db::startTrans();
            if(!empty($_POST))
            {

                file_put_contents(__DIR__.'/pay_notify/alipay.txt',json_encode($_POST)."\r\n",FILE_APPEND);
                $Alipay = new Alipay();

                $verify= $Alipay->verifyNotify($_POST);

                if(!$verify)
                {
                    die("verify fail");
                }

                if($_POST['trade_status']=='TRADE_SUCCESS')
                {
                    $this->successOrder($_POST['out_trade_no'],$_POST['total_amount'],$_POST['buyer_pay_amount'],$_POST['trade_no'],'2','');
                }
                echo "success";
            }else{
                echo "fail";
            }
            Db::commit();
            exit;
        }catch (\Exception $exception){
            Db::rollback();
            echo $exception->getMessage();
            exit;
        }
    }

    public function tonglian(){
        header("Content-type: text/html; charset=gb2312");
        require_once '../../unionpay/AppConfig.php';
        require_once '../../unionpay/AppUtil.php';


        try {

            Db::startTrans();
            if(!empty($_POST))
            {

                file_put_contents(__DIR__.'/pay_notify/tonglian.txt',json_encode($_POST)."\r\n",FILE_APPEND);
                $params = array();
                foreach($_POST as $key=>$val) {//动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
                    $params[$key] = $val;
                }
                if(count($params)<1){//如果参数为空,则不进行处理
                    echo "error";
                    exit();
                }
                if(\AppUtil::ValidSign($params)){//验签成功
                    //此处进行业务逻辑处理
                    if($_POST['trxstatus']=='0000')
                    {
                        $this->successOrder($_POST['out_trade_no'],$_POST['total_amount'],$_POST['buyer_pay_amount'],$_POST['trade_no'],'2','');
                    }
                    echo "success";
                }
                else{
                    echo "erro";
                }

            }else{
                echo "fail";
            }
            Db::commit();
            exit;
        }catch (\Exception $exception){
            Db::rollback();
            echo $exception->getMessage();
            exit;
        }





    }

    /**
     * 支付订单处理
     * @param $order_sn
     * @param $order_price
     * @param $pay_price
     * @param $transaction_id
     * @param $pay_type
     * @param string $pay_time
     * @return bool
     * @throws Exception
     * @throws \app\api\model\ServerException
     * @throws \app\api\model\UserException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function successOrder($order_sn,$order_price,$pay_price,$transaction_id,$pay_type,$pay_time='',$is_mini_pay=0){

        $str = substr($order_sn,0,1);

        if($str=='M'){
            //小程序支付开头默认拼接 字母 M  验证后去掉
            $order_sn = substr($order_sn,1);
            $str = substr($order_sn,0,1);
        }

        if($str=='D'){
            //分销商申请订单支付
            UserDistributorOrder::paySuccess($order_sn,[],$pay_type,$order_price,$pay_price,$transaction_id,$pay_time,$is_mini_pay);
        }elseif($str=='M'){
            //商家等级购买订单
            MerchLevelOrder::paySuccess($order_sn,[],$pay_type,$order_price,$pay_price,$transaction_id,$pay_time,$is_mini_pay);
        }elseif($str=='O'){
            //子订单单独支付或无父订单单独支付
            Order::paySuccess($order_sn,[],$pay_type,$order_price,$pay_price,$transaction_id,$pay_time,$is_mini_pay);
        }elseif($str=='P'){
            //父订单支付
            Order::parentPaySuccess($order_sn,[],$pay_type,$order_price,$pay_price,$transaction_id,$pay_time,$is_mini_pay);
        }elseif($str=='V'){
            //vip会员购买订单
            UserLevelOrder::paySuccess($order_sn,[],$pay_type,$order_price,$pay_price,$transaction_id,$pay_time,$is_mini_pay);
        }elseif($str=='C'){
            //会员充值余额
            Users::paySuccess($order_sn,[],$pay_type,$order_price,$pay_price,$transaction_id,$pay_time,$is_mini_pay);
        }elseif($str=='R'){
            //账期支付成功
            Order::billpaySuccess($order_sn,[],$pay_type,$order_price,$pay_price,$transaction_id,$pay_time,$is_mini_pay);
        }else{
            throw new Exception('未知订单类型');
        }

        return true;
    }
}
